const moment = require("moment");
const superagent = require("superagent");
const { Op } = require("sequelize");

let TEST = false

module.exports = function (app, opts) {
  const synchronizePepFormStatus = app.fs.scheduleInit(
    {
      interval: "*/10 * * * *",// 每10分钟执行一次
      // interval: "* * * * *", // 每分钟执行一次
      immediate: TEST,
      proRun: !TEST,
    },
    async () => {
      console.log('synchronizePepFormStatus','同步表单状态开始')
      const { models } = app.fs.dc;
      const approvalState = {
        'ACTIVE': 1, // 待审批
        'In_OPERATION': 1, // 审批中
        'SUSPENDED': 2, // 撤销
        'EXTERNALLY_TERMINATED': 3, // 驳回
        'COMPLETED': 4 // 通过
      };
      const data = await models.RepairData.findAll({
        where: {
          formStatus: 1,
          procinstId: { [Op.ne]: null }
        },
        attributes: ['procinstId', 'formStatus'],
      });

      const username = "admin";
      const password = "fs-workflow";
      const apiRoot = `${opts.camundarest.host}/${opts.camundarest.root}`;
      const updateOperations = [];

      for (const item of data) {
        const { procinstId, formStatus } = item;
        if (procinstId) {
          const url = `/engine-rest/history/process-instance/${procinstId}`;
          try {
            const response = await superagent.get(`${apiRoot}${url}`).auth(username, password);
            if (response.status === 200) {
              const { state } = response.body;
              const newStatus = approvalState[state];

              if (newStatus !== formStatus) {
                // 如果状态不同，准备更新操作
                updateOperations.push({
                  procinstId,
                  newStatus
                });
              }
            }
          } catch (err) {
            //代表流程被驳回
            if(err.status===404){
              updateOperations.push({
                procinstId,
                newStatus: 3
              });
            }
            console.error(`Failed to fetch process instance ${procinstId}:`, err);
            app.fs.logger.error(`schedule: synchronizePepFormStatus, failed to fetch process instance ${procinstId}: ${err}`);
          }
        }
      }
      if (updateOperations.length) {
        let transaction;
        try {
          transaction = await app.fs.dc.orm.transaction();
          await Promise.all(updateOperations.map(async ({ procinstId, newStatus }) => {
            await Promise.all([
              models.RepairData.update({ formStatus: newStatus }, {
                where: { procinstId },
                transaction
              }),
              models.RepairDataDetail.update({ formStatus: newStatus }, {
                where: { procinstId },
                transaction
              })
            ]);
          }));
          
          await transaction.commit();
        } catch (error) {
          if (transaction) {
            await transaction.rollback();
          }
          console.error("Error in synchronizePepFormStatus:", error);
          app.fs.logger.error(`schedule: synchronizePepFormStatus, error: ${error}`);
        }
      }
    }
  );

  return {
    synchronizePepFormStatus,
  };
};